package com.example.managemyself.util;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 简化的白噪音播放器
 * 只支持雨声白噪音，用于冥想和放松
 */
public class WhiteNoisePlayer {
    
    private static final String TAG = "WhiteNoisePlayer";
    
    // 播放状态枚举
    public enum PlayState {
        STOPPED, PLAYING, PAUSED, LOADING
    }
    
    private static WhiteNoisePlayer instance;
    private final Context context;
    private final ExecutorService executorService;
    
    private MediaPlayer mediaPlayer;
    private PlayState currentState;
    private float currentVolume;
    private boolean isLooping;
    private PlaybackListener playbackListener;
    
    private WhiteNoisePlayer(Context context) {
        this.context = context.getApplicationContext();
        this.executorService = Executors.newSingleThreadExecutor();
        this.currentState = PlayState.STOPPED;
        this.currentVolume = 0.7f;
        this.isLooping = true;
    }
    
    public static synchronized WhiteNoisePlayer getInstance(Context context) {
        if (instance == null) {
            instance = new WhiteNoisePlayer(context);
        }
        return instance;
    }
    
    /**
     * 播放雨声白噪音
     */
    public void play() {
        executorService.execute(() -> {
            try {
                // 停止当前播放
                stopInternal();
                
                setState(PlayState.LOADING);
                
                // 获取或创建MediaPlayer
                MediaPlayer player = getOrCreateMediaPlayer();
                if (player != null) {
                    player.setLooping(isLooping);
                    player.setVolume(currentVolume, currentVolume);
                    player.start();
                    setState(PlayState.PLAYING);
                    Log.d(TAG, "Started playing rain sound");
                } else {
                    setState(PlayState.STOPPED);
                    notifyError("无法加载雨声音频文件");
                }
                
            } catch (Exception e) {
                Log.e(TAG, "Error playing white noise", e);
                setState(PlayState.STOPPED);
                notifyError("播放失败: " + e.getMessage());
            }
        });
    }
    
    /**
     * 暂停播放
     */
    public void pause() {
        executorService.execute(() -> {
            try {
                if (currentState == PlayState.PLAYING && mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        setState(PlayState.PAUSED);
                        Log.d(TAG, "Paused rain sound");
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Error pausing white noise", e);
            }
        });
    }
    
    /**
     * 恢复播放
     */
    public void resume() {
        executorService.execute(() -> {
            try {
                if (currentState == PlayState.PAUSED && mediaPlayer != null) {
                    mediaPlayer.start();
                    setState(PlayState.PLAYING);
                    Log.d(TAG, "Resumed rain sound");
                }
            } catch (Exception e) {
                Log.e(TAG, "Error resuming white noise", e);
            }
        });
    }
    
    /**
     * 停止播放
     */
    public void stop() {
        executorService.execute(this::stopInternal);
    }
    
    private void stopInternal() {
        try {
            if (mediaPlayer != null && (mediaPlayer.isPlaying() || currentState == PlayState.PAUSED)) {
                mediaPlayer.stop();
                mediaPlayer.prepareAsync();
                Log.d(TAG, "Stopped rain sound");
            }
            setState(PlayState.STOPPED);
        } catch (Exception e) {
            Log.e(TAG, "Error stopping white noise", e);
        }
    }
    
    /**
     * 设置音量 (0.0 - 1.0)
     */
    public void setVolume(float volume) {
        this.currentVolume = Math.max(0.0f, Math.min(1.0f, volume));
        
        executorService.execute(() -> {
            try {
                if (mediaPlayer != null) {
                    mediaPlayer.setVolume(currentVolume, currentVolume);
                    Log.d(TAG, "Volume set to: " + currentVolume);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error setting volume", e);
            }
        });
    }
    
    /**
     * 设置循环播放
     */
    public void setLooping(boolean looping) {
        this.isLooping = looping;
        
        executorService.execute(() -> {
            try {
                if (mediaPlayer != null) {
                    mediaPlayer.setLooping(looping);
                    Log.d(TAG, "Looping set to: " + looping);
                }
            } catch (Exception e) {
                Log.e(TAG, "Error setting looping", e);
            }
        });
    }
    
    /**
     * 获取或创建MediaPlayer实例
     */
    private MediaPlayer getOrCreateMediaPlayer() {
        if (mediaPlayer == null) {
            try {
                mediaPlayer = new MediaPlayer();
                
                // 尝试加载雨声音频文件
                int resourceId = context.getResources().getIdentifier(
                    "rain", "raw", context.getPackageName());
                
                if (resourceId != 0) {
                    // 找到音频文件，使用实际音频
                    Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceId);
                    mediaPlayer.setDataSource(context, uri);
                    Log.d(TAG, "使用雨声音频文件");
                } else {
                    // 音频文件不存在，创建静音播放器
                    Log.w(TAG, "雨声音频文件不存在，使用静音模式");
                    return createSilentPlayer();
                }
                
                // 配置音频属性
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();
                mediaPlayer.setAudioAttributes(audioAttributes);
                
                // 设置监听器
                mediaPlayer.setOnPreparedListener(mp -> {
                    Log.d(TAG, "MediaPlayer prepared for rain sound");
                });
                
                mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                    Log.e(TAG, "MediaPlayer error: what=" + what + ", extra=" + extra);
                    notifyError("播放器错误");
                    return true;
                });
                
                mediaPlayer.setOnCompletionListener(mp -> {
                    if (isLooping) {
                        mp.start(); // 手动循环
                    } else {
                        setState(PlayState.STOPPED);
                    }
                });
                
                // 异步准备
                mediaPlayer.prepareAsync();
                
            } catch (Exception e) {
                Log.e(TAG, "创建MediaPlayer失败", e);
                return createSilentPlayer();
            }
        }
        
        return mediaPlayer;
    }
    
    /**
     * 创建静音播放器（当音频文件不存在时的备选方案）
     */
    private MediaPlayer createSilentPlayer() {
        try {
            MediaPlayer silentPlayer = new MediaPlayer();
            Log.w(TAG, "创建静音播放器作为雨声的替代");
            silentPlayer.setLooping(true);
            return silentPlayer;
        } catch (Exception e) {
            Log.e(TAG, "创建静音播放器失败", e);
            return null;
        }
    }
    
    /**
     * 释放资源
     */
    public void release() {
        executorService.execute(() -> {
            try {
                if (mediaPlayer != null) {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                    }
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
                setState(PlayState.STOPPED);
                Log.d(TAG, "WhiteNoisePlayer released");
            } catch (Exception e) {
                Log.e(TAG, "Error releasing WhiteNoisePlayer", e);
            }
        });
    }
    
    /**
     * 设置状态并通知监听器
     */
    private void setState(PlayState newState) {
        PlayState oldState = currentState;
        currentState = newState;
        
        if (playbackListener != null && oldState != newState) {
            // 在主线程中通知监听器
            android.os.Handler mainHandler = new android.os.Handler(android.os.Looper.getMainLooper());
            mainHandler.post(() -> playbackListener.onStateChanged(newState));
        }
    }
    
    /**
     * 通知错误
     */
    private void notifyError(String error) {
        if (playbackListener != null) {
            android.os.Handler mainHandler = new android.os.Handler(android.os.Looper.getMainLooper());
            mainHandler.post(() -> playbackListener.onError(error));
        }
    }
    
    // Getters
    public PlayState getCurrentState() { return currentState; }
    public float getCurrentVolume() { return currentVolume; }
    public boolean isLooping() { return isLooping; }
    public boolean isPlaying() { return currentState == PlayState.PLAYING; }
    
    /**
     * 设置播放监听器
     */
    public void setPlaybackListener(PlaybackListener listener) {
        this.playbackListener = listener;
    }
    
    /**
     * 播放监听器接口
     */
    public interface PlaybackListener {
        void onStateChanged(PlayState newState);
        void onError(String error);
    }
    
    /**
     * 获取播放状态统计
     */
    public PlaybackStatistics getPlaybackStatistics() {
        return new PlaybackStatistics(
                "雨声",
                currentState.name(),
                currentVolume,
                isLooping
        );
    }
    
    /**
     * 播放统计信息类
     */
    public static class PlaybackStatistics {
        private final String currentNoise;
        private final String playState;
        private final float volume;
        private final boolean looping;
        
        public PlaybackStatistics(String currentNoise, String playState, float volume, boolean looping) {
            this.currentNoise = currentNoise;
            this.playState = playState;
            this.volume = volume;
            this.looping = looping;
        }
        
        public String getCurrentNoise() { return currentNoise; }
        public String getPlayState() { return playState; }
        public float getVolume() { return volume; }
        public boolean isLooping() { return looping; }
    }
} 